import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { X, Save, ArrowRight, Info } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Checkbox } from "@/components/ui/checkbox";

// 解析杆塔编号前缀和序号
const parseTowerNumber = (towerNumber) => {
  if (!towerNumber) return { branch: "", number: 0 };
  const match = towerNumber.match(/^([A-Za-z]+)(\d+)$/i);
  if (match && match.length === 3) {
    return { branch: match[1].toUpperCase(), number: parseInt(match[2], 10) };
  }
  if (/^\d+$/.test(towerNumber)) {
    return { branch: "", number: parseInt(towerNumber, 10) };
  }
  return { branch: towerNumber.toUpperCase(), number: 0 };
};

// 生成中间杆塔编号
const generateTowerNumbers = (start, end) => {
  const startParsed = parseTowerNumber(start);
  const endParsed = parseTowerNumber(end);

  if (startParsed.branch !== endParsed.branch) {
    return [];
  }

  const minNum = Math.min(startParsed.number, endParsed.number);
  const maxNum = Math.max(startParsed.number, endParsed.number);
  const towerNumbers = [];

  for (let i = minNum + 1; i < maxNum; i++) {
    towerNumbers.push(startParsed.branch ? `${startParsed.branch}${i}` : `${i}`);
  }

  return startParsed.number > endParsed.number ? towerNumbers.reverse() : towerNumbers;
};

export default function TensionSectionForm({
  tensionSection,
  projects,
  towers,
  crossingPoints = [],
  onSubmit,
  onCancel,
}) {
  const [formData, setFormData] = useState({
    projectId: "",
    name: "",
    startTensionTowerId: "",
    endTensionTowerId: "",
    intermediateTowerIds: [],
    associatedCrossingPointIds: [],
    spanLengths: [],
    description: "",
  });

  const [availableTowers, setAvailableTowers] = useState([]);
  const [orderedTowerIds, setOrderedTowerIds] = useState([]);
  const [prefixMismatch, setPrefixMismatch] = useState(false);
  const [autoFilled, setAutoFilled] = useState(false);
  const [isManualInput, setIsManualInput] = useState([]);
  const [hasUserInteracted, setHasUserInteracted] = useState(false);

  // 杆塔类型标签
  const towerTypeLabels = {
    tensionTower: "耐张塔",
    straightLineTower: "直线塔",
    angleTower: "转角塔",
    branchTower: "分支塔",
  };

  // 初始化项目选择
  useEffect(() => {
    if (tensionSection?.projectId) {
      setFormData((prev) => ({ ...prev, projectId: tensionSection.projectId }));
    } else if (projects.length > 0) {
      setFormData((prev) => ({ ...prev, projectId: projects[0].id }));
    }
  }, [tensionSection, projects]);

  // 根据项目筛选杆塔
  useEffect(() => {
    if (formData.projectId && towers) {
      const filtered = towers.filter(tower => tower.projectId === formData.projectId);
      setAvailableTowers(filtered);

      // 清空无效的选择
      if (formData.startTensionTowerId && !filtered.some(t => t.id === formData.startTensionTowerId)) {
        setFormData(prev => ({ ...prev, startTensionTowerId: "" }));
      }
      if (formData.endTensionTowerId && !filtered.some(t => t.id === formData.endTensionTowerId)) {
        setFormData(prev => ({ ...prev, endTensionTowerId: "" }));
      }
      setFormData(prev => ({ ...prev, intermediateTowerIds: [] }));
      setAutoFilled(false);
    } else {
      setAvailableTowers([]);
      setFormData(prev => ({
        ...prev,
        startTensionTowerId: "",
        endTensionTowerId: "",
        intermediateTowerIds: []
      }));
      setAutoFilled(false);
    }
  }, [formData.projectId, towers]);

  // 初始化表单数据
  useEffect(() => {
    if (tensionSection) {
      const initialStartId = tensionSection.startTensionTowerId || "";
      const initialEndId = tensionSection.endTensionTowerId || "";
      
      const isValidId = (id) => availableTowers.some((t) => t.id === id);
      const validStartId = isValidId(initialStartId) ? initialStartId : "";
      const validEndId = isValidId(initialEndId) ? initialEndId : "";

      const initialCrossingIds = Array.isArray(tensionSection.associatedCrossingPointIds)
        ? tensionSection.associatedCrossingPointIds.map((id) => String(id))
        : [];

      const initialTowerOrder = [
        validStartId,
        ...(tensionSection.intermediateTowerIds || []),
        validEndId,
      ];
      const initialSpanCount = initialTowerOrder.length - 1;
      const orderedSpanLengths = Array.isArray(tensionSection.spanLengths)
        ? tensionSection.spanLengths.slice(0, initialSpanCount)
        : [];
      
      while (orderedSpanLengths.length < initialSpanCount) {
        orderedSpanLengths.push("");
      }

      setFormData({
        projectId: tensionSection.projectId || "",
        name: tensionSection.name || "",
        startTensionTowerId: validStartId,
        endTensionTowerId: validEndId,
        intermediateTowerIds: tensionSection.intermediateTowerIds?.filter(id => isValidId(id)) || [],
        associatedCrossingPointIds: initialCrossingIds,
        spanLengths: orderedSpanLengths.map((val) => parseFloat(val) || ""),
        description: tensionSection.description || "",
      });
      
      setIsManualInput(orderedSpanLengths.map(() => true));
      setAutoFilled(!!tensionSection.intermediateTowerIds?.length);
    } else if (projects.length > 0 && !formData.projectId) {
      setFormData((prev) => ({ ...prev, projectId: projects[0].id }));
    }
  }, [tensionSection, projects, availableTowers]);

  // 检查前缀匹配
  useEffect(() => {
    if (!formData.startTensionTowerId || !formData.endTensionTowerId) {
      setPrefixMismatch(false);
      return;
    }

    const startTower = availableTowers.find((t) => t.id === formData.startTensionTowerId);
    const endTower = availableTowers.find((t) => t.id === formData.endTensionTowerId);

    if (!startTower || !endTower || !startTower.towerNumber || !endTower.towerNumber) {
      setPrefixMismatch(false);
      return;
    }

    const startParsed = parseTowerNumber(startTower.towerNumber);
    const endParsed = parseTowerNumber(endTower.towerNumber);

    if (startParsed.branch !== endParsed.branch) {
      setPrefixMismatch(true);
      if (formData.intermediateTowerIds.length > 0) {
        setFormData((prev) => ({ ...prev, intermediateTowerIds: [] }));
        setAutoFilled(false);
      }
    } else {
      setPrefixMismatch(false);
    }
  }, [formData.startTensionTowerId, formData.endTensionTowerId, availableTowers]);

  // 自动填充中间杆塔（关键修复：恢复原有逻辑）
  useEffect(() => {
    if (prefixMismatch || !formData.startTensionTowerId || !formData.endTensionTowerId || autoFilled) {
      return;
    }

    const startTower = availableTowers.find((t) => t.id === formData.startTensionTowerId);
    const endTower = availableTowers.find((t) => t.id === formData.endTensionTowerId);

    if (startTower && endTower && startTower.towerNumber && endTower.towerNumber) {
      const intermediateNumbers = generateTowerNumbers(startTower.towerNumber, endTower.towerNumber);

      if (intermediateNumbers.length > 0) {
        const intermediateIds = intermediateNumbers
          .map((num) => {
            const tower = availableTowers.find((t) => t.towerNumber === num);
            return tower ? tower.id : null;
          })
          .filter((id) => id !== null && id !== formData.startTensionTowerId && id !== formData.endTensionTowerId);

        const uniqueIntermediates = [...new Set(intermediateIds)];
        setFormData((prev) => ({
          ...prev,
          intermediateTowerIds: uniqueIntermediates,
        }));
        setAutoFilled(true);
      }
    }
  }, [formData.startTensionTowerId, formData.endTensionTowerId, availableTowers, autoFilled, prefixMismatch]);

  // 杆塔顺序与档距联动（关键修复：恢复原有自动填充逻辑）
  useEffect(() => {
    if (formData.startTensionTowerId && formData.endTensionTowerId) {
      const currentTowerIds = [
        formData.startTensionTowerId,
        ...formData.intermediateTowerIds,
        formData.endTensionTowerId,
      ].filter((id, index, self) => self.indexOf(id) === index);

      const requiredSpanCount = currentTowerIds.length - 1;
      const newSpans = [];
      const newManual = [];

      // 构建档距数组，保留已有值
      for (let i = 0; i < requiredSpanCount; i++) {
        if (i < formData.spanLengths.length) {
          newSpans.push(formData.spanLengths[i]);
          newManual.push(isManualInput[i] || false);
        } else {
          newSpans.push("");
          newManual.push(false);
        }
      }

      // 关键修复：自动填充档距值（恢复原有逻辑）
      for (let i = 0; i < requiredSpanCount; i++) {
        const currentTowerId = currentTowerIds[i];
        const currentTower = availableTowers.find((t) => t.id === currentTowerId);

        if (!newManual[i] && (newSpans[i] === "" || newSpans[i] === 0) && currentTower && currentTower.spanToNextTower) {
          newSpans[i] = Number(currentTower.spanToNextTower);
        }
      }

      setOrderedTowerIds(currentTowerIds);
      setFormData((prev) => ({ ...prev, spanLengths: newSpans }));
      setIsManualInput(newManual);
    } else {
      setOrderedTowerIds([]);
      setFormData((prev) => ({ ...prev, spanLengths: [] }));
      setIsManualInput([]);
    }
  }, [formData.startTensionTowerId, formData.endTensionTowerId, formData.intermediateTowerIds, availableTowers]);

  // 表单变更处理
  const handleChange = (field, value) => {
    if (field === "startTensionTowerId" || field === "endTensionTowerId") {
      setAutoFilled(false);
      setIsManualInput([]);
    }
    if (field === "projectId") {
      setAutoFilled(false);
      setIsManualInput([]);
    }
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  // 跨越点选择
  const handleCrossingPointToggle = (cpId) => {
    const stringId = String(cpId);
    setFormData((prev) => {
      const current = new Set(prev.associatedCrossingPointIds || []);
      current.has(stringId) ? current.delete(stringId) : current.add(stringId);
      return {
        ...prev,
        associatedCrossingPointIds: Array.from(current),
      };
    });
  };

  // 添加中间杆塔
  const handleAddIntermediateTower = (towerId) => {
    if (towerId &&
        !formData.intermediateTowerIds.includes(towerId) &&
        towerId !== formData.startTensionTowerId &&
        towerId !== formData.endTensionTowerId &&
        availableTowers.some(t => t.id === towerId)) {
      setFormData((prev) => ({
        ...prev,
        intermediateTowerIds: [...prev.intermediateTowerIds, towerId],
      }));
    }
  };

  // 移除中间杆塔
  const handleRemoveIntermediateTower = (towerId) => {
    setFormData((prev) => ({
      ...prev,
      intermediateTowerIds: prev.intermediateTowerIds.filter((id) => id !== towerId),
    }));
  };

  // 档距值变更
  const handleSpanLengthChange = (index, value) => {
    const numValue = value === "" ? "" : parseFloat(value);
    setFormData((prev) => {
      const newSpans = [...prev.spanLengths];
      if (index >= 0 && index < newSpans.length) {
        newSpans[index] = isNaN(numValue) ? "" : numValue;
      }
      return { ...prev, spanLengths: newSpans };
    });

    setIsManualInput((prev) => {
      const newManual = [...prev];
      newManual[index] = true;
      return newManual;
    });
  };

  // 计算代表档距
  const calculateRulingSpan = (spans) => {
    if (!spans || spans.length === 0) return 0;
    const validSpans = spans.filter((s) => s > 0);
    if (validSpans.length === 0) return 0;

    const sumCubed = validSpans.reduce((sum, l) => sum + Math.pow(l, 3), 0);
    const sumLinear = validSpans.reduce((sum, l) => sum + l, 0);
    return Math.sqrt(sumCubed / sumLinear);
  };

  // 提交表单
  const handleSubmit = (e) => {
    e.preventDefault();

    const validatedSpans = formData.spanLengths.map((s) => {
      const num = parseFloat(s);
      return isNaN(num) || num <= 0 ? 0 : num;
    });

    const hasEmptySpan = validatedSpans.some((s) => s <= 0);
    if (hasEmptySpan) {
      alert("请填写所有有效的档距长度（大于0）");
      return;
    }

    const averageRulingSpan = calculateRulingSpan(validatedSpans);
    const totalLength = validatedSpans.reduce((sum, l) => sum + l, 0);

    const submitData = {
      ...formData,
      spanLengths: validatedSpans,
      averageRulingSpan,
      totalLength,
      id: tensionSection?.id || "",
    };

    onSubmit(submitData);
  };

  // 获取杆塔显示标签
  const getTowerLabel = (towerId) => {
    const tower = availableTowers.find((t) => t.id === towerId);
    if (!tower) return towerId;
    return `${tower.towerNumber} (${towerTypeLabels[tower.type] || tower.type})`;
  };

  const canShowSpanInputs = orderedTowerIds.length >= 2;
  const totalValidSpans = formData.spanLengths
    .filter((s) => s > 0)
    .reduce((sum, s) => sum + s, 0);

  return (
    <Card className="mb-6 shadow-lg border-0">
      <CardHeader className="bg-gradient-to-r from-green-50 to-teal-50 border-b">
        <CardTitle className="flex items-center justify-between">
          <span>{tensionSection ? "编辑勘查单" : "新建勘查单"}</span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="projectId">所属项目 *</Label>
              <Select
                value={formData.projectId}
                onValueChange={(value) => handleChange("projectId", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择项目" />
                </SelectTrigger>
                <SelectContent>
                  {projects.map((p) => (
                    <SelectItem key={`project-${p.id}`} value={p.id}>
                      {p.projectName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="name">勘查单名称 *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleChange("name", e.target.value)}
                placeholder="如: 1#~5#杆勘查单"
                required
              />
            </div>
          </div>

          {/* 起止塔选择 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="startTensionTowerId">起始塔 *</Label>
              <Select
                value={formData.startTensionTowerId}
                onValueChange={(value) => handleChange("startTensionTowerId", value)}
                disabled={!formData.projectId}
              >
                <SelectTrigger>
                  <SelectValue placeholder={formData.projectId ? "选择起始塔" : "请先选择项目"} />
                </SelectTrigger>
                <SelectContent>
                  {availableTowers.map((t) => (
                    <SelectItem key={`start-tower-${t.id}`} value={t.id}>
                      {t.towerNumber} ({towerTypeLabels[t.type] || t.type})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="endTensionTowerId">结束塔 *</Label>
              <Select
                value={formData.endTensionTowerId}
                onValueChange={(value) => handleChange("endTensionTowerId", value)}
                disabled={!formData.projectId}
              >
                <SelectTrigger>
                  <SelectValue placeholder={formData.projectId ? "选择结束塔" : "请先选择项目"} />
                </SelectTrigger>
                <SelectContent>
                  {availableTowers.map((t) => (
                    <SelectItem key={`end-tower-${t.id}`} value={t.id}>
                      {t.towerNumber} ({towerTypeLabels[t.type] || t.type})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 中间杆塔 */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <Label>中间杆塔（按顺序添加）</Label>
              {formData.intermediateTowerIds.length > 0 && !prefixMismatch && (
                <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-200">
                  已自动识别中间杆塔
                </Badge>
              )}
            </div>

            <div className="flex gap-2 mb-2">
              <Select
                onValueChange={handleAddIntermediateTower}
                disabled={prefixMismatch || !formData.projectId}
              >
                <SelectTrigger className="flex-1">
                  <SelectValue
                    placeholder={
                      !formData.projectId
                        ? "请先选择项目"
                        : prefixMismatch
                        ? "前缀不同，无法添加"
                        : "添加中间杆塔"
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  {availableTowers
                    .filter(
                      (t) =>
                        t.id !== formData.startTensionTowerId &&
                        t.id !== formData.endTensionTowerId &&
                        !formData.intermediateTowerIds.includes(t.id)
                    )
                    .map((t) => (
                      <SelectItem key={`intermediate-select-${t.id}`} value={t.id}>
                        {t.towerNumber} ({towerTypeLabels[t.type]})
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-wrap gap-2">
              {formData.intermediateTowerIds.map((towerId, index) => (
                <Badge
                  key={`intermediate-badge-${towerId}-${index}`}
                  variant="secondary"
                  className="flex items-center gap-1"
                >
                  <span className="text-xs text-gray-500">#{index + 1}</span>
                  {getTowerLabel(towerId)}
                  <button
                    type="button"
                    onClick={() => handleRemoveIntermediateTower(towerId)}
                    className="ml-1 hover:text-red-600"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </Badge>
              ))}
            </div>
          </div>

          {/* 杆塔顺序与档距输入 */}
          {canShowSpanInputs && (
            <div className="space-y-4">
              <Alert className="bg-blue-50 border-blue-200">
                <Info className="h-4 w-4 text-blue-600" />
                <AlertDescription className="text-blue-800">
                  系统已识别到 {orderedTowerIds.length} 个杆塔，需要输入 {orderedTowerIds.length - 1} 个档距长度
                </AlertDescription>
              </Alert>

              <div>
                <Label className="text-base font-semibold mb-3 block">
                  杆塔顺序与档距输入
                </Label>
                <div className="space-y-3">
                  {orderedTowerIds.map((towerId, index) => (
                    <div key={`tower-preview-${towerId}-${index}`}>
                      <div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg">
                        <Badge variant="outline" className="font-mono">
                          {index + 1}
                        </Badge>
                        <span className="font-medium">
                          {getTowerLabel(towerId)}
                        </span>
                      </div>
                      {index < orderedTowerIds.length - 1 && (
                        <div className="flex items-center gap-3 my-2 ml-8">
                          <ArrowRight className="w-4 h-4 text-gray-400" />
                          <div className="flex-1">
                            <Label className="text-sm text-gray-600">
                              第 {index + 1} 档距 (m) *
                            </Label>
                            <Input
                              type="number"
                              step="0.1"
                              min="0"
                              value={formData.spanLengths[index] ?? ""}
                              onChange={(e) =>
                                handleSpanLengthChange(index, e.target.value)
                              }
                              placeholder="输入档距长度"
                              className="mt-1"
                              required
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              {totalValidSpans > 0 && (
                <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-gray-600">已填写档距：</span>
                      <span className="font-bold text-green-700 ml-2">
                        {formData.spanLengths.filter((s) => s > 0).length} / {orderedTowerIds.length - 1}
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-600">总长度：</span>
                      <span className="font-bold text-green-700 ml-2">
                        {totalValidSpans} m
                      </span>
                    </div>
                    {formData.spanLengths.filter((s) => s > 0).length === orderedTowerIds.length - 1 && (
                      <>
                        <div>
                          <span className="text-gray-600">代表档距：</span>
                          <span className="font-bold text-green-700 ml-2">
                            {calculateRulingSpan(formData.spanLengths).toFixed(2)} m
                          </span>
                        </div>
                        <div>
                          <span className="text-gray-600">平均档距：</span>
                          <span className="font-bold text-green-700 ml-2">
                            {(totalValidSpans / formData.spanLengths.filter((s) => s > 0).length).toFixed(2)} m
                          </span>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 描述 */}
          <div>
            <Label htmlFor="description">描述</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => handleChange("description", e.target.value)}
              rows={3}
              placeholder="输入勘查单描述信息..."
            />
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <Button type="button" variant="outline" onClick={onCancel}>
              取消
            </Button>
            <Button
              type="submit"
              className="bg-green-600 hover:bg-green-700"
              disabled={
                !formData.projectId ||
                !canShowSpanInputs ||
                formData.spanLengths.some((s) => !s || s <= 0) ||
                prefixMismatch
              }
            >
              <Save className="w-4 h-4 mr-2" />
              {tensionSection ? "更新勘查单" : "创建勘查单"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}